package com.gitee.elf.core.data

import com.gitee.elf.core.data.Serializer.asData
import com.google.gson.*
import java.lang.reflect.Type

class DataList : Data {

    val table = ArrayList<Data>()

    override fun getValue(): Any {
        return table.map { it.getValue() }
    }

    operator fun plusAssign(data: Data) {
        table.add(data)
    }

    fun get(index: Int): Data {
        return table[index]
    }

    fun forEach(func: (Data) -> Unit) {
        table.forEach(func)
    }

    fun size(): Int {
        return table.size
    }

    fun clear() {
        table.clear()
    }

    operator fun minusAssign(element: Data) {
        table.remove(element)
    }

    override fun toString(): String {
        return table.toString()
    }

    override fun clone(): DataList {
        val dataList = DataList()
        this.table.forEach {
            dataList += it.clone()
        }
        return dataList
    }

    @SerializerType(DataList::class)
    class Serializer : JsonSerializer<DataList>, JsonDeserializer<DataList> {

        override fun serialize(src: DataList, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
            return com.gitee.elf.core.data.Serializer.toJsonTree(src.table)
        }

        override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): DataList {
            return json.asData() as DataList
        }

    }
}